import Vue from 'vue'
import VueRouter from 'vue-router'
import { getItem, setItem } from '@/utils/storage.js'
import request from '@/utils/request.js'
import store from '@/store'
import { Toast } from 'vant'

Vue.use(VueRouter)

const routes = [
  {
    path: '/login',
    component: () => import('@/views/Login.vue')
  },
  {
    path: '/',
    component: () => import('@/views/Layout'),
    children: [
      {
        path: '', // 默认子路由
        component: () => import('@/views/Layout/home/home.vue')
      },
      {
        path: '/video',
        component: () => import('@/views/Layout/video/video.vue')
      },
      {
        path: '/qs',
        component: () => import('@/views/Layout/qs/qs.vue')
      },
      {
        path: '/profile',
        component: () => import('@/views/Layout/profile/profile.vue')
      }
    ]
  },
  {
    path: '/user',
    component: () => import('@/views/User')
  },
  {
    path: '/search',
    component: () => import('@/views/Search')
  },
  {
    path: '/article/:articleId',
    name: 'article',
    component: () => import('@/views/Article'),
    props: true
  }
]

const router = new VueRouter({
  routes
})

const expireTime = 1 * 60

router.beforeEach((to, from, next) => {
  const currentTime = Date.now()
  const loginTime = getItem('loginTime')
  const seconed = (currentTime - loginTime) / 1000
  console.log(seconed)
  Toast.loading({
    message: '加载中...',
    forbidClick: true,
    loadingType: 'spinner'
  })
  if (store.state.user && store.state.user.token && seconed > expireTime) {
    request({
      method: 'PUT',
      url: '/v1_0/authorizations'
    }).then(res => {
      console.log(res)
      store.commit('setUser', {
        token: res.data.token,
        refresh_token: store.state.user.refresh_token
      })
      setItem('loginTime', Date.now())
      Toast('亲,进来了')
      next()
    })
  } else {
    Toast('亲,进来了')
    next()
  }
})

export default router
